/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.server.transport.http;

import java.nio.channels.SocketChannel;
import java.util.LinkedList;

import org.creativor.rayson.share.transport.BufferFormatException;
import org.creativor.rayson.share.transport.http.HttpRequestParser;
import org.creativor.rayson.share.transport.nio.ReadBuffer;
import org.creativor.rayson.share.transport.nio.WriteBuffer;

/**
 * Server side HTTP protocol connection.
 * 
 * @author creativor
 */
public class HttpConnection {

	private final WriteBuffer writeBuffer;
	private final ReadBuffer readBuffer;
	private final SocketChannel socketChannel;
	private final HttpRequestParser requestParser;
	private final LinkedList<ServerHttpRequest> requests;

	/**
	 * @param readBuffer
	 * @param writeBuffer
	 * @param requestParser
	 */
	public HttpConnection(final SocketChannel socketChannel,
			final ReadBuffer readBuffer, final WriteBuffer writeBuffer,
			final HttpRequestParser requestParser) {
		this.socketChannel = socketChannel;
		this.readBuffer = readBuffer;
		this.writeBuffer = writeBuffer;
		this.requestParser = requestParser;
		requests = new LinkedList<>();
	}

	/**
	 * Asynchrony read from underling read buffer.
	 * 
	 * @throws BufferFormatException
	 */
	public void asyncRead() throws BufferFormatException {
		// Test whether the buffer has no remaining.
		readBuffer.tryCompact();
		// 1.Consume all the buffered data.
		while (readBuffer.consume() >= 0) {
			if (requestParser.isMessageReady()) {
				final ServerHttpRequest request = requestParser.takeMessage();
				System.out.println("Got server request: " + request);
				this.requests.add(request);
			}
		}
	}

	@Override
	public String toString() {
		final StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("socketChannel:" + this.socketChannel);
		sb.append("}");
		return sb.toString();
	}
}
